package com.LeetCode.why98;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by Aqc on 2017/8/25.
 * 判断一棵树是不是二叉搜索树
 */
public class BST {
    public boolean isValidBST(TreeNode root) {
        //中序遍历法，看是否有序
        if (root == null || (root.left == null && root.right == null)) return true;
        ArrayList<Integer> list = new ArrayList<Integer>();//中序遍历结果存放在list中
        MiddleSearch(root, list);
        int temp = 0, curr = 0;
        Iterator<Integer> iter = list.iterator();
        if (iter.hasNext()) {
            temp = iter.next();
        }
        while (iter.hasNext()) {
            curr = iter.next();
            if (curr <= temp) {
                return false;
            }
            temp = curr;
        }
        return true;
    }

    private void MiddleSearch(TreeNode root, ArrayList<Integer> list) {
        if (root == null) return;
        if (root.left != null) {
            MiddleSearch(root.left, list);
        }
        list.add(root.val);
        if (root.right != null) {
            MiddleSearch(root.right, list);
        }
    }




}
